package com.kaifamiao.jdbc.d0908;

import com.kaifamiao.jdbc.d0908.entity.Users;
import com.mysql.cj.jdbc.MysqlDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class Demo04 {


    public static void main(String[] args) {
        DataSource dataSource = initDataSource();

        QueryRunner runner = new QueryRunner(dataSource);

        try {
            queryMany(runner);
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    public static DataSource initDataSource(){
        String url = "jdbc:mysql://localhost:3306/kfm";
        String user = "root";
        String password = "";

        MysqlDataSource dataSource = new MysqlDataSource();

        dataSource.setURL(url);
        dataSource.setUser(user);
        dataSource.setPassword(password);
        return dataSource;
    }

    public static void insert(QueryRunner runner) throws SQLException {

        String sql = "insert into users(username, password, gender) values(?, ?, ?)";

        System.out.println(runner.update(sql, "kaifamiao", "123456", 1));

//        System.out.println(runner.insert(sql, new ResultSetHandler<Integer>() {
//            @Override
//            public Integer handle(ResultSet resultSet) throws SQLException {
//                if (resultSet.next()){
//                    return resultSet.getInt(1);
//                }
//                return null;
//            }
//        },"kfm", "123456", 1));
    }


    public static void queryOne(QueryRunner runner) throws SQLException{
        String sql = "select * from users where id = ?";

        try {
            Users user = runner.query(sql, new BeanHandler<Users>(Users.class), 1);
            System.out.println(user);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void queryMany(QueryRunner runner) throws SQLException{
        String sql = "select * from users";

        try {
            List<Users> users = runner.query(sql, new BeanListHandler<Users>(Users.class));
            users.forEach(e -> System.out.println(e));
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
